/*******************************************************************************
 * Copyright (c) 2017-2019, org.smartboot. All rights reserved.
 * project name: smart-socket
 * file name: BufferPage.java
 * Date: 2019-12-31
 * Author: sandao (zhengjunweimail@163.com)
 *
 ******************************************************************************/

package com.stylesmile.socket.buffer;


import sun.nio.ch.DirectBuffer;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ByteBuffer分装
 *
 * @author 三刀
 * @version V1.0 , 2018/10/31
 */
public final class ByteBufferWrapper {
    /**
     * 锁 线程安全处理 ，不处理io操作线程不安全
     */
    private final ReentrantLock lock = new ReentrantLock();
    /**
     * 当前缓存页的物理缓冲区
     */
    private final ByteBuffer buffer;
    /**
     * 待回收的虚拟Buffer
     */
//    private final ConcurrentLinkedQueue<VirtualBuffer> cleanBuffers = new ConcurrentLinkedQueue<>();
    /**
     * 当前空闲的虚拟Buffer
     */
//    private final List<VirtualBuffer> availableBuffers;
    /**
     * 内存页是否处于空闲状态
     */
    private boolean idle = true;

    /**
     * @param size   缓存页大小
     * @param direct 是否使用堆外内存
     */
    public ByteBufferWrapper(int size, boolean direct) {
//        availableBuffers = new LinkedList<>();
        this.buffer = allocate0(size, direct);
//        availableBuffers.add(new VirtualBuffer(this, null, buffer.position(), buffer.limit()));
    }

    /**
     * 申请物理内存页空间
     *
     * @param size   物理空间大小
     * @param direct true:堆外缓冲区,false:堆内缓冲区
     * @return 缓冲区
     */
    private ByteBuffer allocate0(int size, boolean direct) {
        return direct ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
    }


    /**
     * 释放内存
     */
    public void release() {
        if (buffer.isDirect()) {
            ((DirectBuffer) buffer).cleaner().clean();
        }
    }


}
